# -*- coding: utf-8 -*-
import socket
import cgi
import logging
import atom.service
import gdata.service
import gdata.spreadsheet
import gdata.spreadsheet.service
import gdata.spreadsheet.text_db
import string
from xml.dom import minidom
import ConfigParser
import socket
import copy
import getopt
import sys


class fetcher():
        
    def __init__(self):    #, email, password):
        self.gd_client = gdata.spreadsheet.service.SpreadsheetsService()

        cfg = ConfigParser.ConfigParser()
        cfg.read('spreadsheet.cfg')  # FIXME
        self.config = dict(cfg._sections)
        self.gd_client.email = self.config['spreadsheet']['email']
        self.gd_client.password = open(self.config['spreadsheet']['password_file']).readline()

        self.gd_client.source = 'gdata client'
        self.gd_client.ProgrammaticLogin()

        self.spreadsheet_key = self.config['spreadsheet']['key'] 
        self.register_sheet_id = self.config['sheet_register']['id']
        self.config_sheet_id = self.config['sheet_config']['id']

        self.user = None
        self.user_raw = None

        self.key = None
        self.keyr = None

        self.feed = None


        # FIXME: raise any errors, not only socket.sslerror
        try:                    
            self.gd_client.ProgrammaticLogin()
        except socket.sslerror, e:
            logging.error('Spreadsheet socket.sslerror: ' + str(e))

    def get_key(self):
        if self.key == None:
            #self.key = copy.copy(self.config['sheet_register'])+copy.copy(self.config['sheet_config'])
            self.key = dict(self.config['sheet_register'].items() + self.config['sheet_config'].items())
                
                        

            for i in self.key:
                self.key[i] = unicode(self.key[i].decode('utf-8'))

            self.keyr = {}

            for i in self.key:
                if( i[0:4] == 'hdr_' ):
                    self.keyr[i[4:]] = self.key[i]

            self.keyr = dict((v,k) for k, v in self.keyr.iteritems())

            # logging.info("key=%s" % self.key)
            # logging.info("keyr=%s" % self.keyr)
        
    # https://spreadsheets.google.com/feeds/list/tnloxD-75v_XqIusPEVJmUA/od6/private/full?sq=%E9%9A%8A%E8%99%9F%3D100203
    def get_user(self, loginid):
        q = gdata.spreadsheet.service.ListQuery()
        q.sq = self.config['sheet_register']['hdr_id']+'='+(loginid)
        
        self.feed = self.gd_client.GetListFeed(self.spreadsheet_key, self.register_sheet_id, query=q)

        if( len(self.feed.entry) < 1 ):
            return None

        self.user_raw = {}
        for i, entry in enumerate(self.feed.entry):
            if isinstance(self.feed, gdata.spreadsheet.SpreadsheetsListFeed):
                for key in entry.custom:
                    if( entry.custom[key].text != None ):
                        self.user_raw[key] = entry.custom[key].text
            else:
                return None

            if( i > 0 ):
                return None

        self.get_key()
        
        self.user = {}

        for i in self.user_raw:
            try:
                self.user[self.keyr[i]] = self.user_raw[i]
                # move those to spreadsheet.cfg
                if self.keyr[i] in ["notice_activity","notice_minor","notice_major","account_permission"]:
                    k = self.keyr[i]
                    self.user[k] = self.user[k].split()    
            except:
                pass

        logging.info(self.user)

        return self.user

    def update_user(self, new_data):
        #feed = gd_client.GetListFeed(key, wksht_id)
        if not isinstance(new_data, dict):
            return False

        logging.info('new_data=%s' % new_data)

        if self.feed == None:
            self.get_user(self.user['id'])
 
        for i in new_data:
            if 'hdr_'+i in self.key:
                k = self.key['hdr_'+i]
                if isinstance(new_data[i], list):
                    self.user_raw[k] = unicode(new_data[i][0])
                else:
                    self.user_raw[k] = unicode(new_data[i])

        entry = self.gd_client.UpdateRow(
            self.feed.entry[0],
            self.user_raw)
        
        self.feed = None

        if isinstance(entry, gdata.spreadsheet.SpreadsheetsList):
            return True
        
        return False


    def clean_userdata(self, new_data):
        if "zip" in new_data and "address" in new_data:
            new_data["address"] = new_data["zip"][0]+" "+new_data["address"][0]
            del new_data["zip"]
        
        for i in ["notice_activity", "notice_major", "notice_minor"]:
            if i in new_data:
                new_data[i] = " ".join(new_data[i])
            else:
                new_data[i] = ""

        for k in ["name_ch","nationality","nationalid","birthday"]:
            if k in new_data:
                del new_data[k]

        return new_data                
            

def main():
    try:
      opts, args = getopt.getopt(sys.argv[1:], "", ["userid="])
    except getopt.error, msg:
      print 'python fetcher.py --userid [userid]'
      sys.exit(2)

    userid = None

    for o, a in opts:
      if o == "--userid":
          userid = a

    if not userid:
        print 'check argument'
        sys.exit(1)

    logging.basicConfig(
        level = logging.INFO,
        format = '%(asctime)s %(levelname)s %(message)s',
    )

    s = fetcher()
    a = s.get_user(userid)
    
    #s.update_user({'passwd':123,'passwdhint':567})

    #a = s.get_user(userid)

    for k, v in a.iteritems():
        print k,v

if __name__ == '__main__':
    main()

